package common;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;

import com.software.mty.shenhao.BuildConfig;

import java.io.File;

import model.Version;

public class DownloadHelper {


    private ServiceConnection conn;
    private IShowDownload showDownload;

    public DownloadHelper(IShowDownload showDownload) {
        this.showDownload = showDownload;
    }


    public void checkUpdate(Version version) {
        //一般还要和忽略的版本做比对。。这里就不累赘了
        if (version != null) {
            if (BuildConfig.VERSION_CODE < version.getVersionCode()) {
                showDownload.showUpdate(version);
            }
        }
    }


    /**
     * 网络下载
     */
    public void downApk(Context context) {
        final String url = "http://10.200.4.123:5000/apk/shenhao.apk";
        if (conn == null)
            conn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
                    DownloadService myService = binder.getService();
                    myService.downApk(APIService.getAPK(), new DownloadService.DownloadCallback() {
                        @Override
                        public void onPrepare() {

                        }

                        @Override
                        public void onProgress(int progress) {
                            showDownload.showProgress(progress);
                        }

                        @Override
                        public void onComplete(File file) {
                            showDownload.showComplete(file);
                        }

                        @Override
                        public void onFail(String msg) {
                            showDownload.showFail(msg);
                        }
                    });
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    //意味中断，较小发生，酌情处理
                }
            };
        Intent intent = new Intent(context, DownloadService.class);
        context.bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    public void unbind(Context context) {
        context.unbindService(conn);
    }


    public interface IShowDownload {
        void showUpdate(Version version);

        void showProgress(int progress);

        void showFail(String msg);

        void showComplete(File file);
    }

}
